package com.jingdianjichi.gateway.auth;

/**
 * ClassName:StpInterfaceImpl
 * Package:com.jingdianjichi.gateway.auth
 * Description:
 *
 * @Author fst
 * @Create 2024/10/9 15:08
 * @Version 1.0
 */

import cn.dev33.satoken.stp.StpInterface;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.jingdianjichi.gateway.auth.entity.AuthPermission;
import com.jingdianjichi.gateway.auth.entity.AuthRole;
import com.jingdianjichi.gateway.auth.redis.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import sun.reflect.generics.visitor.Reifier;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface
{
    private  String PermissionProfix="auth.permission";
    private  String RoleProfix="auth.role";

    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType)
    {
        return AuthList(PermissionProfix,loginId.toString());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        return AuthList(RoleProfix,loginId.toString());
    }

    private List<String> AuthList(String profix,String loginId)
    {
       String authKey=redisUtil.buildKey(profix,loginId);
       String authValue=redisUtil.get(authKey);


       List<String> authList=null;
       if(StringUtils.isEmpty(authValue))
       {
           authList=Collections.emptyList();
       }
       else if(RoleProfix.equals(authKey))
       {
            List<AuthRole> roleList =new Gson().fromJson(authValue,new TypeToken<List<AuthRole>>()
           {
           }.getType());

           authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
       }
       else if(PermissionProfix.equals(PermissionProfix))
       {
          List<AuthPermission> authPermissionList =new Gson().fromJson(authValue,new TypeToken<List<AuthPermission>>(){}.getType());
           authList= authPermissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
       }
       return authList;
    }

}
